﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using ThresholdAssistant.DataContract.Result;
using ThresholdAssistant.Tools;
using ThresholdAssistant.WebAPI.Models;
using System;
using System.ComponentModel;
using System.Linq;

namespace ThresholdAssistant.WebAPI.Filters
{
    /// <summary>
    /// 
    /// </summary>
    public class ModelValidFilter : ActionFilterAttribute
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            var state = context.ModelState;
            if (state.IsValid)
            {
                return;
            }
            var (key, message) = GetFirstError(state);
            var result = new ContractResult()
            {
                SerialNo = SnowflakeNoUtil.GetSerialNo()
            };
            if (Enum.TryParse(message, out ErrorResultEnum errorResultEnum))
            {
               // var desc = GetEnumDesc(errorResultEnum);
                result.SetError(errorResultEnum);
            }
            else
            {
                result.SetError("100001", message);
            }
            context.Result = new JsonResult(result);
        }

        (string key, string message) GetFirstError(ModelStateDictionary state)
        {
            var key = string.Empty;
            var message = string.Empty;
            foreach (var item in state)
            {
                message = item.Value.Errors.FirstOrDefault(p => !string.IsNullOrWhiteSpace(p.ErrorMessage))?.ErrorMessage;
                if (string.IsNullOrWhiteSpace(message))
                {
                    message = item.Value.Errors.FirstOrDefault(o => o.Exception != null)?.Exception.Message;
                }
                if (!string.IsNullOrWhiteSpace(message))
                {
                    key = item.Key;
                    break;
                }
            }
            return (key, message);
        }

        /// <summary>
        /// 获取枚举描述
        /// </summary>
        /// <param name="e"></param>
        /// <returns></returns>
        string GetEnumDesc(Enum e)
        {
            var info = e.GetType().GetField(e.ToString());
            if (info == null)
            {
                return "";
            }
            var attributes = (DescriptionAttribute[])info.GetCustomAttributes(typeof(DescriptionAttribute), false);
            return attributes.Any() ? attributes.First().Description : e.ToString();
        }
    }
}
